import 'package:flutterapp/Base/methodChannel/MethodChannelManager.dart';
import 'package:flutterapp/DirectiveManager.dart';
import 'package:jmessage_flutter/jmessage_flutter.dart';
import 'package:url_launcher/url_launcher.dart';

class JpushManager {
//  c851c9731b5ad9ca
  static JmessageFlutter JMessage;
  static const JPUSH_APP_KEY = "ca72c5d6739629af07e4e59b";
  static const _PSW = "9527";
  static const ERR_CODE_REGISTERED = "898001";

  static void init({bool isDebug = true}) {
    JMessage = JmessageFlutter();
    JMessage.setDebugMode(enable: isDebug);
    JMessage.init(isOpenMessageRoaming: false, appkey: JPUSH_APP_KEY);
    JMessage.applyPushAuthority(
        new JMNotificationSettingsIOS(sound: true, alert: true, badge: true));
    addAllListener();
  }

  static autoLogin(String userName) async {
    try {
      var res = await JMessage.userRegister(username: userName, password: _PSW);
      JpushManager.login(userName);
    } catch (e) {
      print("JpushManager: ===autoLogin=== $e");
      if (e.code == ERR_CODE_REGISTERED) {
        JpushManager.login(userName);
      }
    }
  }

  static login(String userName) {
    JMessage.login(username: userName, password: _PSW).then((value) {
      print("JpushManager: ===login success=== ");
    }).catchError((err) {
      print("JpushManager: ===login failed=== $err");
    });
  }

  static addAllListener() {
    JMessage.addReceiveMessageListener((msg) async {
      print(
          'listener receive event - message ： ${msg.toJson()} ${msg.runtimeType}');
      MethodChannelManager.getInstance().invoke(MethodTypes.LIGHT_ON);
      Future.delayed(Duration(seconds: 1), () async {
        DirectiveManager.dispatch(msg);
      });
    });
  }

  static sendMsg(String targetDeviceId, String dirCode, String args) async {
    JMSingle type = JMSingle.fromJson({"username": targetDeviceId});
    JMMessageSendOptions option =
        JMMessageSendOptions.fromJson({"needReadReceipt": true});
    JMTextMessage msg = await JMessage.sendTextMessage(
        type: type,
        text: "time: ${DateTime.now()}",
        extras: {"code": dirCode, "args": args},
        sendOption: option);
    print("JpushManager: ${msg.toJson()}");
  }
}
